//
//  HeadImgViewController.m
//  WGFGlobalHouses
//
//  Created by waiguofang on 15/4/16.
//  Copyright (c) 2015年 waiguofang. All rights reserved.
//   个人中心－－上传头像界面

#import "HeadImgViewController.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "AFNetworking.h"


@interface HeadImgViewController ()<UIActionSheetDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>
- (IBAction)saveBtn;
@property (weak, nonatomic) IBOutlet UIImageView *photoLv;
@property(nonatomic,assign) BOOL isUpload;

@end

@implementation HeadImgViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    // Do any additional setup after loading the view from its nib.
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
    
    self.isUpload = NO;
    [self addGestureToPhotoLv];
   }
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/**
 *  给“上传头像”图片添加点击手势
 */
-(void)addGestureToPhotoLv
{
    self.photoLv.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(getPhoto)];
    [self.photoLv addGestureRecognizer:tap];
}

/**
 *  点击“上传照片”获取照片
 */
-(void)getPhoto
{
    UIActionSheet *sheet = [[UIActionSheet alloc]initWithTitle:@"提示" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照",@"从相册中选择", nil];
    [sheet showInView:self.view];
}

#pragma mark UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex;
{
    UIImagePickerController *pc = [[UIImagePickerController alloc]init];
    pc.delegate = self;
    if (buttonIndex == 0) {//拍照
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
        {
            pc.allowsEditing = YES;
            [self presentViewController:pc animated:YES completion:nil];
        }else
        {
            UIAlertView  *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相机不可用" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];
        }
    }else{//从相册中选择
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
        {
            [pc setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            pc.allowsEditing = YES;
            [self presentViewController:pc animated:YES completion:nil];
        }
        else{
            UIAlertView  *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"相册不可用" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
            [alter show];

        }
    }
}

#pragma mark imagePickerController的代理
/**
 *  选择照片完成
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info;
{
    self.isUpload = YES;
    NSString *str = [info objectForKey:UIImagePickerControllerMediaType];
    if ([str isEqualToString:(NSString *)kUTTypeImage])//是image
    {
        UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
        [self dismissViewControllerAnimated:YES completion:^{
            [[UIApplication sharedApplication]setStatusBarHidden:NO];
        }];
        self.photoLv.image =image;
    }
}

-(void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}
/**
 *  保存头像
 */
- (IBAction)saveBtn
{
    if (self.isUpload)
    {
        [self uplodeUserImage];
    }
    else
    {
        UIAlertView *alter = [[UIAlertView alloc]initWithTitle:@"提示" message:@"请选择一张图片" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alter show];
    }
}

//然后通过AFNetworking上传图片到服务器，
/*
 {userId}/{type}/{pictures}
 */
- (void)uplodeUserImage {
//    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
//    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
//    UserModel *um = [UserModel sharedModel];
//    NSData *imageData = UIImageJPEGRepresentation(_photoIv.image, 1);
//    NSDictionary *parameters =@{@"userId":um.userId,@"type":[NSNumber numberWithInt:0]};
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/plain"];
//    [manager POST:UP_IMG parameters:parameters constructingBodyWithBlock:^(id formData) {
//        [formData appendPartWithFileData:imageData name:@"pictures" fileName:@"avatar.jpg" mimeType:@"image/jpeg"];
//        
//    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSDictionary *result = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
//        NSLog(@"dict = %@",result);
//        
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"上传失败!  error = %@",error.localizedDescription);
//    }];
//    
//    AppDelegate *del = [AppDelegate sharedInstance];
//    del.userIcon = UIImageJPEGRepresentation(_photoIv.image, 0.5);
//    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"上传成功！" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
//    [alert show];
}

@end
